package com.dongdong.mq;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdong.mapper.TbSeckillGoodsMapper;
import com.dongdong.mapper.TbSeckillOrderMapper;
import com.dongdong.pojo.TbSeckillGoods;
import com.dongdong.pojo.TbSeckillOrder;
import com.dongdong.util.IdWorker;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Component
@RocketMQMessageListener(topic = "seckill-topic",consumerGroup = "seckill-group")
public class SeckillMQConsumer implements RocketMQListener<Map> {
    @Resource
    private TbSeckillOrderMapper seckillOrderMapper;
    @Resource
    private TbSeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void onMessage(Map map) {
        long id = Long.parseLong(map.get("id").toString());
        String username = (String) map.get("username");
        IdWorker idWorker = new IdWorker();
        long orderId = idWorker.nextId();
        try {
            TbSeckillGoods goods = seckillGoodsMapper.selectByPrimaryKey(id);
            TbSeckillOrder order = new TbSeckillOrder();
            order.setId(orderId);
            order.setUserId(username);
            order.setStatus("1");//未支付
            order.setSeckillId(goods.getId());
            order.setSellerId(goods.getSellerId());
            order.setMoney(goods.getCostPrice());//秒杀价
            order.setCreateTime(new Date());
            //以下为支付成功以后需要添加的字段
            //order.setPayTime();
            //order.setReceiver();
            //order.setTransactionId();
            //保存数据库
            seckillOrderMapper.insertSelective(order);
            System.out.println("订单保存成功");
            redisTemplate.boundHashOps("order").put(orderId,username);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("订单保存失败");
            redisTemplate.boundHashOps("order").put(-1L,username);
        }

    }
}
